package myTimer;

import java.util.PriorityQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: tao
 * Date: 2023-12-05
 * Time: 18:20
 */
//专门放任务的类
class MyTimer3Task implements Comparable<MyTimer3Task>{
    //要执行的代码
    private Runnable runnable;
    //要到啥时候才执行的时间
    private long time;
    //构造方法
    public MyTimer3Task(Runnable runnable, long time) {
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + time;
    }
    @Override
    public int compareTo(MyTimer3Task o) {
        return (int) (this.time - o.time);
    }
    //获取时间的方法
    public long getTime() {
        return this.time;
    }
    //执行runnable的方法
    public void run() {
        runnable.run();
    }
}
class MyTimer3 {
    Object locker = new Object();
    //创建一个线程，负责扫描任务的线程
    Thread t = null;
    //创建一个优先级队列，存放任务
    PriorityQueue<MyTimer3Task> queue = new PriorityQueue<>();
    //写一个入队列的方法
    public void schedule(Runnable runnable, long time) {
        synchronized (locker) {
            //把要执行的代码和时间放进任务中
            MyTimer3Task task = new MyTimer3Task(runnable, time);
            //入队列
            queue.offer(task);
            locker.notify();
        }
    }
    //构造方法，创建一个线程，让这个线程来判断操作
    public MyTimer3() {
        t = new Thread(() -> {
            while (true) {
                synchronized (locker) {
                    try {
                        //判断队列是不是空的，是空的就要等待
                        while (queue.isEmpty()) {
                            locker.wait();
                        }
                        //不为空时，就要判断到没到时间，到时间了才会执行run的代码，没到也继续等待
                        long curTime = System.currentTimeMillis();
                        MyTimer3Task task = queue.peek();
                        if(curTime >= task.getTime()) {
                            //到时间了，出队列，执行run代码
                            queue.poll();
                            task.run();
                        } else {
                            //没到时间，就要等待
                            locker.wait(task.getTime() - curTime);
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        t.start();
    }
}
public class TimerTest3 {
    public static void main(String[] args) {
        MyTimer3 timer = new MyTimer3();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 3000");
            }
        }, 3000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 2000");
            }
        }, 2000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 1000");
            }
        }, 1000);
        System.out.println("hello main");
    }
}
